from PIL import Image
import numpy as np
import os
import threading

import analyze_image as ai


def get_images(directory_name):
    """
    获取文件夹下的所有图片
    """
    images = []
    for filename in os.listdir(r"./" + directory_name):
        image = Image.open(directory_name + "/" + filename)
        images.append((filename, image))
    return images


def resize_image(image, width=4406, height=2480):
    """ 
    修改图片尺寸
    """
    return image.resize((width, height))


def calc_image(image):
    """
    计算图片中每个颜色的数量
    """
    img = np.array(image)
    width = img.shape[1]
    height = img.shape[0]

    color_data = {}
    for row in range(height):
        print(f'图片计算中{format(row/height*100, ".2f")}%。。。。', flush=True)
        for col in range(width):
            rgb = tuple(img[row, col])
            color_data[rgb] = 1 if rgb not in color_data else color_data[rgb] + 1

    # for row in range(width):
    #     print(f'图像像素点计算中{format(row/width*100, ".2f")}%。。。。', end='\r')
    #     for col in range(height):
    #         rgb = tuple(img[col, row])
    #         color_data[rgb] = 1 if rgb not in color_data else color_data[rgb] + 1

    img_data = [[item[0]]*item[1] for item in color_data.items()]  # [[()]]
    img_data = [i for arr in img_data for i in arr]  # [()]
    img_data = np.array(img_data)  # [[]]
    img_data = img_data.reshape(height, width, 3)
    return img_data


def test():
    filename = 'test2.jpg'
    image = Image.open('./input/' + filename)
    image = resize_image(image)
    img_data = calc_image(image)  
    img = Image.fromarray(img_data)
    # img.save('./output/output_' + item[0])
    img.show()


def deal_image(filename):
    image = Image.open("inputs/" + filename)
    image = resize_image(image)
    img_data = ai.calc_image(image, 3, 'row')  
    img = Image.fromarray(img_data)
    img.save('./outputs/output_' + filename)
    img_data = ai.calc_image(image, 3, 'row', True)  
    img = Image.fromarray(img_data)
    img.save('./outputs/output_sort_' + filename)
    os.remove("inputs/" + filename)



def main():
    folder = os.getcwd() + '\\outputs'
    if not os.path.exists(folder):
        os.makedirs(folder)
    # num = 0
    for filename in os.listdir(r"./inputs"):
        # deal_image(filename)
        # if num == 4:
        #     break
        threading.Thread(target=deal_image, args=(filename, )).start()
        # num += 1


if __name__ == '__main__':
    # test()
    main()
    print('程序已完成')

